package com.bridgeintelligent.tag.webserver.security.sql;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class SqlCheckInterceptor implements HandlerInterceptor {

    public List<String> excludes = new ArrayList<>();

    private static String badStr = "update|delete|insert|drop|\\*|truncate";

    private static String[] ARRAY;
    static {
        ARRAY = badStr.split("\\|");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //过滤掉不校验的接口
        if (handleExcludeURL(request,response)){
            return true;
        }
        //校验参数是否含有非法字符
        Map<String,String[]> parametersMap = request.getParameterMap();
        Iterator<String> iterator = parametersMap.keySet().iterator();
        while (iterator.hasNext()) {
            String[] params = parametersMap.get(iterator.next());
            for (int i = 0; i < params.length; i++) {
                if (sqlValidate(params[i])){
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter printWriter = response.getWriter();
                    printWriter.write("参数不合法!!!");
                    return false;
                }
            }
        }
        return true;
    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response){
        if (CollectionUtils.isEmpty(excludes)){
            return false;
        }
        String url = request.getRequestURI();
        for (String pattern: excludes){
            /**
             * 此处需要根据自己的匹配规则去校验是否要走filter
             */
            Pattern p = Pattern.compile("^"+pattern);
            Matcher m = p.matcher(url);
            if (m.find()){
                return true;
            }
        }
        return false;
    }

    //效验
    protected static boolean sqlValidate(String str){
        for (String bad : ARRAY) {
            if (str.toLowerCase().contains(bad)){
                return true;
            }
        }
        return false;
    }

    private void out(HttpServletResponse response, String json){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(null!=out){
                out.write(json);
                out.flush();
                out.close();
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }


}
